<template>
	<view class="login-container">
		<view class="login-container-bg"></view>
		<view class="login-main">
			<u-gap height="120rpx"></u-gap>
			<view class="slogan">
				<view class="slogan-hd title-black">Hi,欢迎使用</view>
				<view class="slogan-bd title-black font-primary">{{ title }}</view>
			</view>

			<view class="login-tips">
				<view class="login-tips-main">
					<view class="login-tips-title">登录提示</view>
					<block v-if="errorTips">
						<view class="login-tips-content u-line-2 mb30">{{ errorTips || '--' }}</view>
						<u-button type="primary" size="small" @click="onRefresh" text="刷新页面"></u-button>
					</block>
					<block v-else>
						<view class="login-tips-content">
							<view class="fcc">
								<u-loading-icon size="20"></u-loading-icon>
								<text class="ml20">登录跳转中...</text>
							</view>
						</view>
					</block>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		APP_TITLE,
		APP_ID
	} from '@/env.js';
	export default {
		name: 'Login',
		data() {
			return {
				title: APP_TITLE,
				appId: APP_ID,
				errorTips: ''
			};
		},
		onLoad() {
			if (!this.token) {
				this.wxLogin();
			}
		},
		methods: {
			onRefresh() {
				window.location.href = '/teacher-app/login';
			},
			wxLogin() {
				if (!!this.errorTips) this.errorTips = '';

				const code = this.getUrlCode().code || null;
				if (!!code) {
					// 已静默登录
					const query = this.$Route.query;
					// if (query?.id) {
					// 从二维码进入才有参数，域名直接进入没有任何参数，但是 user_type 是必须的
					const {
						is_bind,
						user_type,
						id,
						sign
					} = query;
					uni.showLoading({
						title: '授权登录中...'
					});
					this.$store
						.dispatch('Login', {
							is_bind: is_bind || '',
							user_type: user_type || 'teacher',
							id: id || '',
							sign: sign || '',
							code
						})
						.then(() => {
							uni.hideLoading();
							this.$Router.replaceAll({
								path: '/'
							});
						})
						.catch((error) => {
							this.errorTips = error.message || '登录失败,尝试刷新页面或联系管理员!';
							uni.hideLoading();
						});
					// }
				} else {
					let local = window.location.href;
					window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${this.appId}&redirect_uri=${encodeURIComponent(
					local
				)}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`;
				}
			},
			/**
			 * 截取url中的code方法
			 */
			getUrlCode() {
				var url = location.search;
				var theRequest = new Object();
				if (url.indexOf('?') != -1) {
					var str = url.substr(1);
					var strs = str.split('&');
					for (var i = 0; i < strs.length; i++) {
						theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1];
					}
				}
				return theRequest;
			}
		}
	};
</script>

<style lang="scss">
	@import './index.scss';
</style>